//
//  TimerScrollView.swift
//  MevosSwift
//
//  Created by roy on 2017/4/21.
//  Copyright © 2017年 roy. All rights reserved.
//

import UIKit
import Kingfisher

protocol TimerScrollViewDelegate {
    func scrollToIndexOfPage(index:Int)
    func tapActionIndexOfPage(index:Int)
}

class TimerScrollView: UIView,UIScrollViewDelegate {

    var count : Int = 0
    var timer : Timer!
    var timeDelegate : TimerScrollViewDelegate?
    var scrollView : UIScrollView?
    var pageCT : UIPageControl?
    
    /*
     params:
     array : 图片URL集合
     contentOffSetIndex : 偏移位置
     */
    func configScrollView(array:Array<Any>,contentOffsetIndex:Int) {
        
        count = array.count
        self.clipsToBounds = false
        self.backgroundColor = UIColor.white
        scrollView = UIScrollView(frame:self.bounds)
        scrollView?.delegate = self
        scrollView?.contentSize = CGSize(width:CGFloat(array.count+2) * self.frame.size.width,height:self.frame.size.height)
        scrollView?.isPagingEnabled = true
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.showsHorizontalScrollIndicator = false
        self.addSubview(scrollView!)
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: Selector(("tapAction")))
        scrollView?.addGestureRecognizer(tap)
        
        self.createImageViews(array: array, contentOffsetIndex: contentOffsetIndex)
        self.configPageControl(currentPage: contentOffsetIndex)
        
        timerBegin()
        
    }
    
    func createImageViews(array:Array<Any>,contentOffsetIndex:Int){
        for i in 0 ..< array.count{
            var url : String!
            if i == 0 { url = array[array.count-1] as! String
            }else if i == array.count + 1 {
                url = array[0] as! String
            }else{ url = array[i-1] as! String}
            
            let imageView = UIImageView(frame: CGRect(x:CGFloat(i)*self.frame.size.width,y:0,width:self.frame.size.width, height:self.frame.size.height))
            //imageView.kf.setImage(with: url as! Resource?)
            imageView.kf.setImage(with: url as! Resource?, placeholder: UIImage(named: "mrt"), options: nil, progressBlock: nil, completionHandler: nil)
            scrollView?.addSubview(imageView)
        }
        scrollView?.contentOffset = CGPoint(x:CGFloat(contentOffsetIndex+1)*self.frame.size.width,y:0)
    }
    
    func configPageControl(currentPage:Int){
        pageCT = UIPageControl(frame:CGRect(x:0,y:self.frame.size.height-30.0,width:self.frame.size.width,height:15))
        pageCT?.pageIndicatorTintColor = UIColor.gray
        pageCT?.currentPageIndicatorTintColor = UIColor.white
        pageCT?.currentPage = currentPage
        pageCT?.numberOfPages = count
        self.addSubview(pageCT!)
        
    }
    
    //开启timer
    func timerBegin(){
        if timer != nil {
            timer.invalidate()
            timer = nil
        }
        
        timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: Selector(("timerRun:")), userInfo: nil, repeats: true)
        RunLoop.main.add(timer, forMode: .commonModes)
    }
    
    //暂停
    func timerPause(){
        if timer != nil {
            timer.invalidate()
            timer = nil
        }
    }
    
    func timerRun(runTimer:Timer)  {
        let offsetX = scrollView?.contentOffset.x
        UIView.animate(withDuration: 0.4, animations: { 
            () -> Void in self.scrollView?.contentOffset = CGPoint(x:offsetX!+self.frame.size.width,y:0)
        }) { (boolValue:Bool) -> Void in
            self.resetContentOffSet()
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        timerPause()
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        timerBegin()
    }
    //改变scrollView上的图片
    func resetContentOffSet(){
        if scrollView!.contentOffset.x < self.frame.size.width {
            scrollView!.contentOffset = CGPoint(x:self.frame.size.width*CGFloat(count),y:0)
        }
        
        if scrollView!.contentOffset.x > self.frame.size.width * CGFloat(count) {
            scrollView!.contentOffset = CGPoint(x:self.frame.size.width, y:0)
        }
        
        let index = Int((scrollView!.contentOffset.x - self.frame.size.width) / self.frame.size.width)
        pageCT?.currentPage = index
        timeDelegate?.scrollToIndexOfPage(index: index)
    }
    //手势
    func tapAction(tap:UITapGestureRecognizer){
        let scrollViewX = scrollView?.contentOffset.x
        let index = Int((scrollViewX! - self.frame.size.width)/self.frame.size.width)
        timeDelegate?.tapActionIndexOfPage(index: index)
    }

}
